//package org.ly.uap.client.validation;
//
//import java.io.BufferedReader;
//import java.io.ByteArrayInputStream;
//import java.io.DataOutputStream;
//import java.io.IOException;
//import java.io.InputStreamReader;
//import java.net.HttpURLConnection;
//import java.net.URL;
//import java.util.ArrayList;
//import java.util.Calendar;
//import java.util.Date;
//import java.util.HashMap;
//import java.util.Iterator;
//import java.util.List;
//import java.util.Map;
//import java.util.TimeZone;
//import java.util.UUID;
//import javax.net.ssl.HttpsURLConnection;
//
//import org.apache.commons.logging.Log;
//import org.ly.uap.client.authentication.AttributePrincipal;
//import org.ly.uap.client.authentication.AttributePrincipalImpl;
//import org.ly.uap.client.util.CommonUtils;
//import org.opensaml.SAMLAssertion;
//import org.opensaml.SAMLAttribute;
//import org.opensaml.SAMLAttributeStatement;
//import org.opensaml.SAMLAuthenticationStatement;
//import org.opensaml.SAMLException;
//import org.opensaml.SAMLNameIdentifier;
//import org.opensaml.SAMLResponse;
//import org.opensaml.SAMLStatement;
//import org.opensaml.SAMLSubject;
//import org.opensaml.XML;
//import org.opensaml.XML.ParserPool;
//
//public final class Saml11TicketValidator extends AbstractUrlBasedTicketValidator {
//    private long tolerance = 1000L;
//
//    public Saml11TicketValidator(String casServerUrlPrefix) {
//        super(casServerUrlPrefix);
//    }
//
//    protected String getUrlSuffix() {
//        return "samlValidate";
//    }
//
//    protected void populateUrlAttributeMap(Map<String, String> urlParameters) {
//        String service = (String) urlParameters.get("service");
//        urlParameters.remove("service");
//        urlParameters.remove("ticket");
//        urlParameters.put("TARGET", service);
//    }
//
//    protected void setDisableXmlSchemaValidation(boolean disabled) {
//        if (disabled) {
//            XML.parserPool.setDefaultSchemas(null, null);
//        }
//    }
//
//    protected Assertion parseResponseFromServer(String response) throws TicketValidationException {
//        try {
//            String removeStartOfSoapBody = response.substring(response.indexOf("<SOAP-ENV:Body>") + 15);
//            String removeEndOfSoapBody = removeStartOfSoapBody.substring(0, removeStartOfSoapBody.indexOf("</SOAP-ENV:Body>"));
//            SAMLResponse samlResponse = new SAMLResponse(new ByteArrayInputStream(removeEndOfSoapBody.getBytes()));
//
//            if (!samlResponse.getAssertions().hasNext()) {
//                throw new TicketValidationException("No assertions found.");
//            }
//
//            for (Iterator iter = samlResponse.getAssertions(); iter.hasNext(); ) {
//                SAMLAssertion assertion = (SAMLAssertion) iter.next();
//
//                if (!isValidAssertion(assertion)) {
//                    continue;
//                }
//                SAMLAuthenticationStatement authenticationStatement = getSAMLAuthenticationStatement(assertion);
//
//                if (authenticationStatement == null) {
//                    throw new TicketValidationException("No AuthentiationStatement found in SAML Assertion.");
//                }
//                SAMLSubject subject = authenticationStatement.getSubject();
//
//                if (subject == null) {
//                    throw new TicketValidationException("No Subject found in SAML Assertion.");
//                }
//
//                SAMLAttribute[] attributes = getAttributesFor(assertion, subject);
//                Map personAttributes = new HashMap();
//                for (SAMLAttribute samlAttribute : attributes) {
//                    List values = getValuesFrom(samlAttribute);
//
//                    personAttributes.put(samlAttribute.getName(), values.size() == 1 ? values.get(0) : values);
//                }
//
//                AttributePrincipal principal = new AttributePrincipalImpl(subject.getNameIdentifier().getName(), personAttributes);
//
//                Object authenticationAttributes = new HashMap();
//                ((Map) authenticationAttributes).put("samlAuthenticationStatement::authMethod", authenticationStatement.getAuthMethod());
//
//                return new AssertionImpl(principal, (Map) authenticationAttributes);
//            }
//        } catch (SAMLException e) {
//            throw new TicketValidationException(e);
//        }
//
//        throw new TicketValidationException("No Assertion found within valid time range.  Either there's a replay of the ticket or there's clock drift. Check tolerance range, or server/client synchronization.");
//    }
//
//    private boolean isValidAssertion(SAMLAssertion assertion) {
//        Date notBefore = assertion.getNotBefore();
//        Date notOnOrAfter = assertion.getNotOnOrAfter();
//
//        if ((assertion.getNotBefore() == null) || (assertion.getNotOnOrAfter() == null)) {
//            this.log.debug("Assertion has no bounding dates. Will not process.");
//            return false;
//        }
//
//        long currentTime = getCurrentTimeInUtc().getTime();
//
//        if (currentTime + this.tolerance < notBefore.getTime()) {
//            this.log.debug("skipping assertion that's not yet valid...");
//            return false;
//        }
//
//        if (notOnOrAfter.getTime() <= currentTime - this.tolerance) {
//            this.log.debug("skipping expired assertion...");
//            return false;
//        }
//
//        return true;
//    }
//
//    private SAMLAuthenticationStatement getSAMLAuthenticationStatement(SAMLAssertion assertion) {
//        for (Iterator iter = assertion.getStatements(); iter.hasNext(); ) {
//            SAMLStatement statement = (SAMLStatement) iter.next();
//
//            if ((statement instanceof SAMLAuthenticationStatement)) {
//                return (SAMLAuthenticationStatement) statement;
//            }
//        }
//
//        return null;
//    }
//
//    private SAMLAttribute[] getAttributesFor(SAMLAssertion assertion, SAMLSubject subject) {
//        List attributes = new ArrayList();
//        for (Iterator iter = assertion.getStatements(); iter.hasNext(); ) {
//            SAMLStatement statement = (SAMLStatement) iter.next();
//
//            if ((statement instanceof SAMLAttributeStatement)) {
//                SAMLAttributeStatement attributeStatement = (SAMLAttributeStatement) statement;
//
//                if (subject.getNameIdentifier().getName().equals(attributeStatement.getSubject().getNameIdentifier().getName())) {
//                    for (Iterator iter2 = attributeStatement.getAttributes(); iter2.hasNext(); ) {
//                        attributes.add((SAMLAttribute) iter2.next());
//                    }
//                }
//            }
//        }
//        return (SAMLAttribute[]) attributes.toArray(new SAMLAttribute[attributes.size()]);
//    }
//
//    private List<?> getValuesFrom(SAMLAttribute attribute) {
//        List list = new ArrayList();
//        for (Iterator iter = attribute.getValues(); iter.hasNext(); ) {
//            list.add(iter.next());
//        }
//        return list;
//    }
//
//    private Date getCurrentTimeInUtc() {
//        Calendar c = Calendar.getInstance();
//        c.setTimeZone(TimeZone.getTimeZone("UTC"));
//        return c.getTime();
//    }
//
//    protected String retrieveResponseFromServer(URL validationUrl, String ticket) {
//        String MESSAGE_TO_SEND = "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\"><SOAP-ENV:Header/><SOAP-ENV:Body><samlp:Request xmlns:samlp=\"urn:oasis:names:tc:SAML:1.0:protocol\"  MajorVersion=\"1\" MinorVersion=\"1\" RequestID=\"" + UUID.randomUUID().toString() + "\" IssueInstant=\"" + CommonUtils.formatForUtcTime(new Date()) + "\">" +
//                "<samlp:AssertionArtifact>" + ticket +
//                "</samlp:AssertionArtifact></samlp:Request></SOAP-ENV:Body></SOAP-ENV:Envelope>";
//
//        HttpURLConnection conn = null;
//        try {
//            conn = (HttpURLConnection) validationUrl.openConnection();
//            if ((this.hostnameVerifier != null) && ((conn instanceof HttpsURLConnection))) {
//                ((HttpsURLConnection) conn).setHostnameVerifier(this.hostnameVerifier);
//            }
//            conn.setRequestMethod("POST");
//            conn.setRequestProperty("Content-Type", "text/xml");
//            conn.setRequestProperty("Content-Length", Integer.toString(MESSAGE_TO_SEND.length()));
//            conn.setRequestProperty("SOAPAction", "http://www.oasis-open.org/committees/security");
//            conn.setUseCaches(false);
//            conn.setDoInput(true);
//            conn.setDoOutput(true);
//
//            DataOutputStream out = new DataOutputStream(conn.getOutputStream());
//            out.writeBytes(MESSAGE_TO_SEND);
//            out.flush();
//            out.close();
//
//            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
//            StringBuilder buffer = new StringBuilder(256);
//            String line;
//            while ((line = in.readLine()) != null) {
//                buffer.append(line);
//            }
//            String str1 = buffer.toString();
//            return str1;
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        } finally {
//            if (conn != null)
//                conn.disconnect();
//        }
//
//    }
//
//    public void setTolerance(long tolerance) {
//        this.tolerance = tolerance;
//    }
//}
//
